<?php

namespace app\admin\controller;

use app\common\controller\Backend;
use think\Db;
/**
 * 考试记录
 *
 * @icon fa fa-circle-o
 */
class Record extends Backend
{

    /**
     * Record模型对象
     * @var \app\admin\model\Record
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\Record;
    }



    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */


    /**
     * 查看
     */
    public function index()
    {
        //当前是否为关联查询
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $list = $this->model
                    ->with(['user','exam','testpaper'])
                    ->where($where)
                    ->order($sort, $order)
                    ->paginate($limit);

            foreach ($list as $row) {
                
                $row->getRelation('user')->visible(['name']);
				$row->getRelation('exam')->visible(['title']);
				$row->getRelation('testpaper')->visible(['title','grades']);
            }

            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
        return $this->view->fetch();
    }

    /**
     * 考试记录详情
     *
     * @param [type] $ids
     * @return void
     */
    public function detail($ids = null)
    {
        if($this->request->isPost()){
            $id = input('record_id');
            $question_id = input('question_id');
            $grade = input('grade');

            Db::startTrans();
            try {
                $res = Db::name('answers')->where([
                    "record_id"=>$id,
                    "question_id"=>$question_id,
                ])->update([
                    "grade"=>$grade
                ]);
    
                $score = Db::name('answers')->where("record_id",$id)->sum('grade');
                $this->model->update([
                    "score"=>$score,
                    "id"=>$id
                ]);

                Db::commit();
            } catch (\Exception $e) {
                //throw $th;
                Db::rollback();

                $this->error($e->getMessage());
            }
           

            if($res){

                $this->success('修改成功',null,[
                    "score"=>$score
                ]);
            }
            else{
                $this->error('修改失败');
            }
        }
        $row = $this->model->get($ids);
        if(!$row){
            $this->error(__('No Results were found'));
        }

        $answers = Db::name('answers')->alias('a')
        ->join('questions q','a.question_id = q.id')
        ->where('a.record_id',$ids)
        ->field('a.*,q.title,q.typedata,q.answerscontent')
        ->select();   
        // halt($answers);  
        $type = [
            "1"=>"单选题",
            "2"=>"多选题",
            "3"=>"判断题",
            "4"=>"填空题",
            "5"=>"问答题",
        ];

        $options = ["A","B","C","D","E","F"];
        foreach ($answers as $key => &$value) {
            $value["type"] =  $type[$value["typedata"]];

            $answer_right = json_decode($value["answer_right"],true) ?? [];
            $answer_mine = json_decode($value["answer_mine"],true) ?? [];

            if(in_array($value["typedata"],["1","2","3"])){
                if($value["typedata"] == '3'){
                    // 判断题

                    foreach ($answer_right as &$v) {
                        $v = ["对","错"][$v];
                    }
    
                    foreach ($answer_mine as &$v) {
                        $v = ["对","错"][$v];
                    }
                }
                else{

                    foreach ($answer_right as &$v) {
                        $v = $options[$v];
                    }
    
                    foreach ($answer_mine as &$v) {
                        $v = $options[$v];
                    }
                }
            }

            $value["answer_right"] = implode(',',$answer_right);
            $value["answer_mine"] = implode(',',$answer_mine);

        }   
        $this->view->assign('answers',$answers);
        $this->view->assign('row',$row);

        $this->view->assign('id',$ids);
        return $this->view->fetch();
    }

}
